package com.yhsimon.controller;

import com.yhsimon.pojo.Book;
import com.yhsimon.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    @Qualifier("bookServiceImpl")
    private BookService bookService;

    @RequestMapping("/allBooks")
    public String list(Model model){
        List<Book> books = bookService.queryAllBooks();
        System.out.println(books);
        model.addAttribute("books", books);
        return "allBooks";
    }

    @RequestMapping("/toAddPage")
    public String toAddPage(){
        return "addBook";
    }

    @RequestMapping("/addBook")
    public String addBook(Book book){
        bookService.addBook(book);
        return "redirect:/book/allBooks";
    }

    @RequestMapping("/toUpdatePage")
    public String toUpdatePage(Model
                                           model,int id){
        Book book = bookService.queryBookById(id);
        model.addAttribute("book", book);
        return "updateBook";
    }

    @RequestMapping("/updateBook")
    public String updateBook(Model model,Book book){
        bookService.updateBook(book);
        Book  newBook = bookService.queryBookById(book.getBookID());
        model.addAttribute("book", newBook);
        return "redirect:/book/allBooks";
    }

    @RequestMapping("/delete/{bookId}")
    public String deleteById(@PathVariable("bookId") int id){
        bookService.deleteById(id);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/queryBookByName")
    public String queryBookByName(String bookName,Model model){
        List<Book> books=new ArrayList<>();
        if(bookName.equals("")){
            books=bookService.queryAllBooks();
        }else{
            books = bookService.queryBookByName(bookName);
        }

        model.addAttribute("books",books);
        return "allBooks";
    }
}
